<?php
namespace Web\Controller;
use Think\Controller;
class ChatController extends Controller {
   public function _initialize()  
    {  
        header("Content-Type: text/html; charset=utf-8");

    } 
     public function _empty($name){
        //把所有城市的操作解析到city方法
        $this->nul($name);
    }
    
    //注意 city方法 本身是 protected 方法
    protected function nul($name){
        //和$name这个城市相关的处理
         echo "<h1>404</h1>";
         echo "没有这个地址:".$name;
    }
    /**
     * 聊天室开启
     * 渲染出当前拥有的数据
     * @return [type] [description]
     */
    public function panel_chat(){
      $record_data=M('record')
                ->alias('a')
                ->join('bm_chat b ON a.chat_id=b.chat_id','LEFT')
                ->join('bm_chat_group e ON a.chat_id=e.chat_id','LEFT')
                ->join('bm_web_user c ON e.y_id=c.web_id')
                ->group('record_id')
                ->where('a.chat_id='.session('chat.chat_id'))
                ->select();
      $this->assign('record_data',$record_data);
        /******当前用户信息******/
       $res_chat_data=M('from_user_group')->where('chat_id='.session('chat.chat_id'))->find();
        /******当前用户信息******/
        /******当前用户提交客户资料******/
       $chat_lccdc_data=M('lccdc')
                  ->alias('a')
                  ->join('bm_chat b ON a.chat_id=b.chat_id',"LEFT")
                  ->join('bm_search_data  c ON a.data_id=c.data_id',"LEFT")
                  ->join('bm_shenqing  d ON a.cd_id=d.cd_id',"LEFT")
                  ->join('bm_web_user_data  e ON a.c_id=e.c_id',"LEFT")
                  ->where('b.chat_id='.session('chat.chat_id'))
                  ->find();
        /****当前用户数据***/
        /******当前用户提交客户资料******/
      $this->assign('message',$res);
      $this->assign('chat_lccdc_data',xml_encode($chat_lccdc_data));
      $this->assign('from_user_group_data',$res_chat_data);
      $this->assign('from_user_group',json_encode($res_chat_data));
      $this->display();
    }
    /****************************全ajax处理聊天室数据************************************/

    /**
     * 发生信息 
     * @return [type] [description]
     * 
     */
    public function send_msg(){
        
        $data=$_POST;
        $arr['from_user']=$data['from_user'];
        $arr['to_user']=$data['to_user'];
        $arr['chat_id']=$data['chat_id'];
        $arr['time']=date('Y/m/d h:i:s');
        if($_SESSION['role']['role']==1){
           $arr['role']=1;
        }
        else{
           $arr['role']=0;
        }
        if($data['send_time']){
           $arr['send_time']=$data['send_time'];
           //1232553600  
        }
        if($data['web_id']){
            $where_re_ts['web_id']=$data['web_id'];
            $r=M('web_user')->where($where_re_ts)->find();
            if($r['re_time']){
                $r1=M('web_user')->where($where_re_ts)->setInc('re_time',time());
                $r2=M('web_user')->where($where_re_ts)->setInc('re_sec');
             }
             else{
                $r1=M('web_user')->where($where_re_ts)->save('re_time',time());
                $r2=M('web_user')->where($where_re_ts)->save('re_sec');
                $r3=M('web_user')->where($where_re_ts)->save('start_time',time());
             }
        }

        if($_SESSION['user']['web_type']==2){

          $arr['q_web_id']=$_SESSION['user']['web_id'];
        }
        $arr['msg']=$data['msg'];
        $res=M('record')->data($arr)->add();
        if($res){
            $msg['code']=1;
            $msg['message']='提交成功';
            $msg['data']=$res.$r1.$r2;
        }
        else{
            $msg['code']=2;
            $msg['message']='提交失败';  
        }
        $this->ajaxReturn($msg);
    }


    /**
     * 在线聊天获取最新一(多条)条数据
     */
    public function update_record(){
        if($_POST&&IS_AJAX){
            $where['chat_id']=$_POST['chat_id'];
            $where['record_id']=array('gt',$_POST['record_id']);
            $where['to_user']=array('like','%'.$_POST['to_user_group_id'].'%');
            if($_POST['chat_id']&&$_POST['record_id']){
                $res=M('record')->where($where)->select();
                if($res){
                    $msg['code']=1;
                    $msg['message']='查询成功';
                    $msg['data']=$res;
                }
                else{
                    $msg['code']=2;
                    $msg['message']="没有最新数据";
                }
            }
            else{
                $msg['code']=3;
                $msg['message']='条件不足';
            }
        }
        else{
            $msg['code']=4;
            $msg['message']='请用ajax提交数据';
        }
        $this->ajaxReturn($msg);
    }
    /**
     * 判断渠道是否已经添加到聊天室
     */
    public function ajax_jud(){
        if(IS_POST&&IS_AJAX){
            if($_POST['chat_id']&&$_POST['y_id']&&$_POST['goods_id']){

                $data_arr=$_POST;
                if($_POST){
                    $ck_add_res=M('chat_group')->where($data_arr)->find();
                    if($ck_add_res){
                        $msg['code']=1;
                        $msg['message']='已经添加了'; 

                    }
                    else{
                        $msg['code']=2;
                        $msg['message']='没有添加'; 
                    }
                }
            }
            else{
                $msg['code']=3;
                $msg['message']='数据不完整';
            }
        }
        else{
            $msg['code']=4;
            $msg['mesage']='请求格式错误';
        }
        $this->ajaxReturn($msg);
    }
    /**
     * 添加银行职员到自己的聊天室
     */
    
    public function add_chat_group(){
        if(IS_POST&&IS_AJAX){
            if($_POST['chat_id']&&$_POST['y_id']&&$_POST['goods_id']){
                $data_arr=$_POST;
                if($_POST){
                    $ck_add_res=M('chat_group')->where($data_arr)->find();
                    if($ck_add_res){
                        $msg['code']=5;
                        $msg['message']='已经添加了'; 
                        $this->ajaxReturn($msg);
                    }
                }
                $add_res=M('chat_group')->data($data_arr)->add();
                if($add_res){
                   /***********************收信息一方to_user*****************************/
                        $to_user_data['to_user_group']=$_POST['y_id'];
                        $to_user_data['chat_id']=session('chat.chat_id');
                        $to_user_data['goods_id']=$_POST['goods_id'];
                        $to_user_temp=M('to_user_group')->data($to_user_data)->add();
                        $to_data=M('to_user_group')->where('to_user_group_id='.$to_user_temp)->find();
                        if(isset($_SESSION['chat']['to_user_group'])){
                          $_SESSION['chat']['to_user_group'][0]=$to_data;
                        }
                        else{
                          $_SESSION['chat']['to_user_group'][count($_SESSION['chat']['to_user_group'])+1]=$to_data;
                        }
                   /***********************收信息一方to_user*****************************/
                    $msg['code']=1;
                    $msg['message']='添加成功'; 
                    $msg['cg_id']=$to_user_temp;
                }
                else{
                    $msg['code']=2;
                    $msg['message']='数据不完整'; 
                }
            }
            else{
                $msg['code']=3;
                $msg['message']='数据不完整';
            }
        }
        else{
            $msg['code']=4;
            $msg['mesage']='请求格式错误';
        }
        $this->ajaxReturn($msg);
    }



    /****************************全ajax处理聊天室数据************************************/
   
    /**
     * 添加渠道前判断渠道是否已经进入来天室
     * 没有进去微信外部发送一条信息
     * 添加银行职员之前ajax判断时候加入聊天室
     */
   public function ajax_cue(){
       $where['chat_id']=I('post.chat_id');
       $where['y_id']=I('post.y_id');
       $where['goods_id']=I('post.goods_id');
       $cue=M('chat_group')->where($where)->find();
       if(IS_AJAX&&IS_POST&&!$cue){
        /********************************************/
                $wechat_user=M('web_user')->where('web_id='.I('post.y_id'))->find();
                $where['wechat_id']=$wechat_user['wechat_id'];
                $wechat=M('wechat')->where($where)->find();
                $appid=$wechat['appid'];
                $appsecret=$wechat['appsecret'];
                $api=new \Com\WechatAuth($appid,$appsecret);
                $chat_id=I('post.chat_id');
                $web_id=I('post.y_id');
                $f_web_id=session('user.web_id');
                $from_user_group_id=I('post.from_user_group_id');
                $goods_id=I('post.goods_id');
                $wechat_id=$_SESSION['wechat_data'][1]['wechat_id'];
                $openid=M('wechat_bind')->where('bind_id='.$wechat_user['bind_id'])->getField('openid');
                $arr['u_name']=get_web_f_mesage($_SESSION['user']['web_id']);
                $arr['litter_name']=M('goods')->where('id='.I('post.goods_id'))->getField('litter_name');
                if($wechat_id&&$chat_id&&$web_id&&$goods_id&&$f_web_id&&$from_user_group_id){
                  $url=preg_replace('# #', '',"http://pgl.oaio.online/index.php/Web/Chat/qudao_link/wechat_id/$wechat_id/chat_id/$chat_id/web_id/$web_id/goods_id/$goods_id/f_web_id/$f_web_id/from_user_group_id/$from_user_group_id");
                  $re=D('Wxauthorise')->temp_message($web_id,$arr,$url);
                  if($re['errcode']==0){
                    $msg['code']=1;
                    $msg['message']='添加用户';
                  }
                  else{
                    $msg['code']=3;
                    $msg['message']='发送通知信息失败';
                  }
                }
                else{
                    $msg['code']=4;
                    $msg['message']='条件不足';
                }
        /********************************************/
       }
       else{
          $msg['code']=2;
          $msg['message']='该用户对应该产品已经存在聊天室';
       }

       $this->ajaxReturn($msg);
   } 
    /**
     * 聊天室用户列表
     * @return [type] [description]
     */
    public function ajax_load_bank_list(){
        if(IS_AJAX&&IS_POST&&$_POST['chat_id']){
            $where['chat_id']=$_POST['chat_id'];
            $bank_list=M('chat_group')
                        ->alias('a')
                        ->join('bm_web_user b ON a.y_id=b.web_id','LEFT')
                        ->join('bm_to_user_group c ON a.y_id=c.to_user_group and a.goods_id=c.goods_id','LEFT')
                        ->where('a.chat_id='.$where['chat_id'].' and c.chat_id='.$where['chat_id'])
                       //->field('a.*,a.chat_id,b.goods_id')
                       //->group('goods_id')
                        ->select();
                        foreach ($bank_list as $key => $value) {
                            $bank_list[$key]['region_web_pro_id']=re_region_address($bank_list[$key]['web_pro_id']);
                            $bank_list[$key]['region_web_city_id']=re_region_address($bank_list[$key]['web_city_id']);
                            $bank_list[$key]['region_web_area_id']=re_region_address($bank_list[$key]['web_area_id']);
                        }
            $msg['code']=1;
            $msg['message']='获取成功';
            $msg['data']=$bank_list;
        }
        else{
            $msg['code']=2;
            $msg['message']='请求方式错误';
        }
        $this->ajaxReturn($msg);
    }
    /**************************针对渠道银行职员聊天处理方案链接进去方案********************************/
    public function qudao_link(){
        if(!session('wechat_data')||!session('wechat_data.0.openid')){
           $_SESSION['wechat_data']='';
           $this->code(); 
        }
        /************检查点击链接用户是否合法**************/
        $session_openid=$_SESSION['wechat_data'][0]['openid'];
        $w_openid['openid']=$session_openid;
        $session_user=M('wechat_bind')
                      ->alias('a')
                      ->join('bm_web_user b ON a.bind_id=b.bind_id','LEFT')
                      ->join('bm_chat_group c ON b.web_id=c.y_id','LEFT')
                      ->where($w_openid)
                      ->find();
        if($session_user){
               /*****************银行职员跳转进入聊天室***********************/
                /**
                 * 银行职员看到数据单产品
                 */
            $wechat_id=I('get.wechat_id');
            $chat_id=I('get.chat_id');
            $web_id=I('get.web_id');
            $goods_id=I('get.goods_id');
            $f_web_id=I('get.');
            $from_user_group_id=I('get.from_user_group_id');//业务员发送消息id
            $where_to_user_group['to_user_group']=$web_id;//array('LIKE',$web_id);
            $where_to_user_group['chat_id']=$chat_id;//array('LIKE',$chat_id);
            $where_to_user_group['goods_id']=$goods_id;
            $to_user_group_id=M('to_user_group')->where($where_to_user_group)->getField('to_user_group_id');
            $where_chat_group['chat_id']=$chat_id;
            $where_chat_group['goods_id']=$goods_id;
            $where_chat_group['y_id']=$web_id;
            $chat_group=M('chat_group')->where($where_chat_group)->find();
            if($to_user_group_id&&$chat_group){
              $where_fro['from_user_group_id']=$from_user_group_id;
              $fom_ids=M('from_user_group')->where($where_fro)->find();
                if($fom_ids){
                    $oa['to_user']=array('like','%'.$to_user_group_id.'%');
                    $oa['from_user']=array('like','%'.$to_user_group_id.'%');
                    $oa['_logic'] = 'or';
                    $temp_res=M('web_user')->where('web_id='.$session_user['web_id'])->find();
                    session('user',$temp_res);
                    $where_record['_complex'] = $oa;
                    $record_data=M('record')
                                ->alias('a')
                                ->join('bm_chat_group b ON a.chat_id=b.chat_id','LEFT')
                                ->join('bm_web_user c ON b.y_id=c.web_id','LEFT')
                                ->group('record_id')
                                ->where('a.chat_id='.$chat_id)
                                ->where($where_record)
                                ->select();
                             
                    $chat_lccdc_data=M('lccdc')
                                    ->alias('a')
                                    ->join('bm_chat b ON a.chat_id=b.chat_id',"LEFT")
                                    ->join('bm_search_data  c ON a.data_id=c.data_id',"LEFT")
                                    ->join('bm_shenqing  d ON a.cd_id=d.cd_id',"LEFT")
                                    ->join('bm_web_user_data  e ON a.c_id=e.c_id',"LEFT")
                                    ->where('b.chat_id='.$chat_id)
                                    ->find();
                    $this->assign('chat_lccdc_data',xml_encode($chat_lccdc_data));
                    $this->assign('json_record_data',json_encode($record_data));

                    $this->assign('record_data',$record_data);
                    /************角色转换银行职员变成发送方**************/
                    $new_from_data['from_user_group_id']=$to_user_group_id;
                    $new_from_data['to_user_group_id']=$from_user_group_id;
                    $new_from_data['chat_id']=$chat_id;
                    $new_from_data['goods_id']=$goods_id;
                    $new_from_data['web_id']=$web_id;
                    $this->assign('my_new_fom_data',$new_from_data);
                    $this->assign('new_fom_data',json_encode($new_from_data));
                    /************角色转换银行职员变成发送方**************/
                }
                else{
                  echo "<script>alert('用户发送数据不全');</script>";die;
                }
            }
            else{

              echo "<script>alert('没有用户数据,用户未添加你如例如聊天室');</script>";die;
            }

            $this->display();
               /*****************银行职员跳转进入聊天室***********************/ 
        }
        else{

            $this->show('<h1>非法操作请确保点击用户是否本人绑定手机</h1>');
        }


    }
    /**************************针对渠道银行职员聊天处理方案链接进去方案********************************/
    /************************************银行职员进入聊天室常规方案**************************************/
    public function qudao_chat(){
            $chat_id=I('get.chat_id');
            $web_id=session('user.web_id');
            $goods_id=I('get.goods_id');
            $f_web_id=I('get.');
            $from_user_group_id=I('get.from_user_group_id');//业务员发送消息id
            $where_to_user_group['to_user_group']=$web_id;//array('LIKE',$web_id);
            $where_to_user_group['chat_id']=$chat_id;//array('LIKE',$chat_id);
            $where_to_user_group['goods_id']=$goods_id;
            $to_user_group_id=M('to_user_group')->where($where_to_user_group)->getField('to_user_group_id');
            $where_chat_group['chat_id']=$chat_id;
            $where_chat_group['goods_id']=$goods_id;
            $where_chat_group['y_id']=$web_id;
            $chat_group=M('chat_group')->where($where_chat_group)->find();
            if($to_user_group_id&&$chat_group){
              $where_fro['from_user_group_id']=$from_user_group_id;
              $fom_ids=M('from_user_group')->where($where_fro)->find();
                if($fom_ids){
                    $oa['to_user']=array('like','%'.$to_user_group_id.'%');
                    $oa['from_user']=array('like','%'.$to_user_group_id.'%');
                    $oa['_logic'] = 'or';
                    $where_record['_complex'] = $oa;
                    $where_record['c.web_id']=session('user.web_id');
                    $where_record['b.goods_id']=$goods_id;
                    $record_data=M('record')
                                ->alias('a')
                                ->join('bm_chat_group b ON a.chat_id=b.chat_id','LEFT')
                                ->join('bm_web_user c ON b.y_id=c.web_id')
                                ->group('record_id')
                                ->where('a.chat_id='.$chat_id)
                                ->where($where_record)
                                ->select();
                    $chat_lccdc_data=M('lccdc')
                                    ->alias('a')
                                    ->join('bm_chat b ON a.chat_id=b.chat_id',"LEFT")
                                    ->join('bm_search_data  c ON a.data_id=c.data_id',"LEFT")
                                    ->join('bm_shenqing  d ON a.cd_id=d.cd_id',"LEFT")
                                    ->join('bm_web_user_data  e ON a.c_id=e.c_id',"LEFT")
                                    ->where('b.chat_id='.$chat_id)
                                    ->find();
                    $this->assign('chat_lccdc_data',xml_encode($chat_lccdc_data));
                    $this->assign('json_record_data',json_encode($record_data));           
                    $this->assign('record_data',$record_data);
                    /************角色转换银行职员变成发送方**************/
                    $new_from_data['from_user_group_id']=$to_user_group_id;
                    $new_from_data['to_user_group_id']=$from_user_group_id;
                    $new_from_data['chat_id']=$chat_id;
                    $new_from_data['goods_id']=$goods_id;
                    $new_from_data['web_id']=$web_id;
                    $this->assign('my_new_fom_data',$new_from_data);
                    $this->assign('new_fom_data',json_encode($new_from_data));
                    /************角色转换银行职员变成发送方**************/
                }
                else{
                  echo "<script>alert('用户发送数据不全');</script>";die;
                }
            }
            else{
              echo "<script>alert('没有用户数据,用户未添加你如例如聊天室');</script>";die;
            }
            $this->display("Chat/qudao_link");
    }
    /************************************银行职员进入聊天室常规方案**************************************/
    /***********************聊天室开关处理******************************/
    public function ajax_state_chat(){
       if(IS_AJAX&&IS_POST){
          if(I('post.chat_id')){
              $where_post['chat_id']=$_POST['chat_id'];
              //$where_post['state']=$_POST['state'];
              $chat=M('chat')->where($where_post)->find();
              if($chat['first_user']=session('user.web_id')){
                 $where_chat_id['chat_id']=$chat['chat_id'];
                 $new_data['state']=I('post.state');
                 $new_state_chat=M('chat')->where($where_chat_id)->data($new_data)->save();
                 if($new_state_chat){
                    $msg['code']=1;
                    $msg['message']='修改聊天室状态成功';
                    $msg['state']='聊天室原来状态'.$chat['state'].',聊天室修改状态'.I('post.state');
                    $msg['data']=$new_state_chat;
                 }
                 else{
                    $msg['code']=2;
                    $msg['message']='修改聊天室失败';
                    $msg['state']='聊天室原来状态'.$chat['state'].',聊天室修改状态'.I('post.state');
                    $msg['data']=$new_state_chat;
                 }
              }
              else{
                $msg['code']=3;
                $msg['message']='操作用户非按揭员';
                $msg['data']=array($chat['first_user'],session('user.web_id'));
              }
          }
          else{
            $msg['code']=4;
            $msg['message']='传送参数错误';
            $msg['data']=array("state",'chat_id',I('post.'));
          }
       }
       else{
         $msg['code']=5;
         $msg['message']='请求方式错误';
       }
       $this->ajaxReturn($msg);
    }
    /***********************聊天室开关处理******************************/
    /***********************获取微信数据**********************************/
    /*
     * 微信获取code换取当前用户信息
     * Enter description here ...
     */
    public  function code(){
        $wechat=M('wechat')->where('wechat_id='.$_GET['wechat_id'])->find();

        $APPID=$wechat['appid'];

        $REDIRECT_URI='http://pgl.oaio.online/index.php/Web/Chat/getcode?appid='.$APPID."&&appsecret=".$wechat['appsecret'].'&&wechat_id='.$_GET['wechat_id']."&&chat_id=".$_GET['chat_id']."&&web_id=".$_GET['web_id']."&&goods_id=".$_GET['goods_id']."&&from_user_group_id=".$_GET['from_user_group_id'];

        $scope='snsapi_base';//不需要授权

        //$scope='snsapi_userinfo';//需要授权
        //
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';

        header("Location:".$url);
        
    }
    
    
   /*
    * 利用code获取access_token等个人用户信权
    * @DateTime:    [2018-04-23 16:13:50]
    */
    public function  getcode(){
            $wechat_id=$_GET['wechat_id'];
            $appid=$_GET['appid'];
            $appsecret=$_GET['appsecret'];
            $code = $_GET["code"]; 
            $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code ";
            $ch = curl_init($get_token_url);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, true); 
            // 抓取URL并把它传递给浏览器
            $res=curl_exec($ch);
            //解析json 

            //session(null);
            // 关闭cURL资源，并且释放系统资源
            curl_close($ch);
            $res=strstr($res, "{");
            $_SESSION['wechat_data'][0]=json_decode($res,true);
            $_SESSION['wechat_data'][1]=$_GET;
            $this->qudao_link();

      
    }
    /***********************获取微信数据**********************************/
    
}